# -*- coding = utf-8 -*-

# @time:2024/10/28 15:17

# Author:hjx

# @File:wc.py

# @Software:PyCharm

# 主程序文件，包含文本统计的逻辑。

import sys
import re


def count_characters(filename):
    with open(filename, 'r', encoding='utf-8') as file:
        text = file.read()
        return len(text)


def count_words(filename):
    with open(filename, 'r', encoding='utf-8') as file:
        text = file.read()
        words = re.findall(r'\b\w+\b', text)
        # 查找所有由字母、数字或下划线组成的单词，并将这些单词作为字符串列表返回。每个单词都是完整的，不会包含标点符号或空格等分隔符。
        return len(words)


def count_sentences(filename):
    with open(filename, 'r', encoding='utf-8') as file:
        text = file.read()
        sentences = re.split(r'[.!?]', text)
        return len([s for s in sentences if s.strip()])


def count_lines(filename):
    with open(filename, 'r', encoding='utf-8') as file:
        return sum(1 for _ in file)


def count_code_lines(filename):
    code_lines = 0
    empty_lines = 0
    comment_lines = 0
    with open(filename, 'r', encoding='utf-8') as file:
        for line in file:
            stripped = line.strip()
            if stripped.startswith("#") or stripped.startswith("//"):
                comment_lines += 1
            elif not stripped:
                empty_lines += 1
            else:
                code_lines += 1
    return code_lines, empty_lines, comment_lines


def main():
    if len(sys.argv) < 3:
        print("Usage: wc.py [option] [filename]")
        sys.exit(1)

    option = sys.argv[1]
    filename = sys.argv[2]

    if option == '-c':
        print(f"Character count: {count_characters(filename)}")
    elif option == '-w':
        print(f"Word count: {count_words(filename)}")
    elif option == '-s':
        print(f"Sentence count: {count_sentences(filename)}")
    elif option == '-l':
        print(f"Line count: {count_lines(filename)}")
    elif option == '--code':
        code, empty, comment = count_code_lines(filename)
        print(f"Code lines: {code}, Empty lines: {empty}, Comment lines: {comment}")
    else:
        print("Invalid option. Use -c, -w, -s, -l, or --code.")


if __name__ == "__main__":
    main()